import React, { Component } from 'react';
import axios from 'axios';
import cookie from 'react-cookies';
import MenuHead from '../comm/menuHead';
import Table from '../comm/table';
import TableL from '../comm/table_l';

class Role extends Component {
  state = {
    cur_tab: "roleList",
    roleQuery: "",
    roleHead: [{en: 'role', ch: '角色'},],
    roleData: [],
    roleDataShow: [],
    roleList_count: 0,
    pageList: [],
    pageHead: [{en: 'abs_path', ch: '目录'},],
    pageListLeft: [],
    pageListRight: [],
    addRoleName: "",
    add_role_input_read_only: false,
    add_or_alter_role: "",
  }
  queryRoleList = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/queryRole", {
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.setState({
        roleData: res.data.role,
        roleDataShow: res.data.role,
        roleList_count: res.data.role.length,
      })
    }).catch((err) => {
      alert(err)
    })
    axios.post("/app/queryPageList", {
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.setState({
        pageList: res.data.page_dir,
      })
    }).catch((err) => {
      alert(err)
    })
  }
  batchDelRoleList = (records) => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    let roleData = this.state.roleDataShow;
    let roleList = [];
    for(let i = 0; i < roleData.length; i++){
      if(records.indexOf(roleData[i]["id"]) !== -1){
        roleList.push(roleData[i]["role"]);
      }
    }
    axios.post("/app/delRole", {
      "role_list": roleList,
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.queryRoleList();
    }).catch((err) => {
      alert(err);
    })
  }
  modifyRoleList = (data) => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    this.setState({
      cur_tab: "roleDetail",
      addRoleName: data["role"],
      add_role_input_read_only: true,
      add_or_alter_role: "updateRole",
    })
    axios.post("/app/queryRoleDetail", {
      "role": data["role"],
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      let page_path = res.data.page_path;
      let left = [];
      let right = [];
      let pageList = this.state.pageList;
      for(let i = 0; i < pageList.length; i++){
        if(page_path.indexOf(pageList[i]["page_path"]) === -1) {
          left.push(pageList[i]);
        } else {
          right.push(pageList[i]);
        }
      }
      this.setState({
        pageListLeft: left,
        pageListRight: right,
      })
    }).catch((err) => {
      alert(err)
    })
  }
  addRole = () => {
    this.setState({
      cur_tab: "roleDetail",
      add_role_input_read_only: false,
      pageListLeft: this.state.pageList,
      pageListRight: [],
      add_or_alter_role: "addRole",
    })
  }
  add_or_alter_role = (roleName, page_list) => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/" + this.state.add_or_alter_role, {
      "role": roleName,
      "page_list": page_list,
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.setState({
        addRoleName: "",
        cur_tab: "roleList",
      })
      this.queryRoleList();
    }).catch((err) => {
      alert(err);
    })
  }
  filterRoleQuery = (e) => {
    let role = e.target.value;
    let f_role = [];
    let t_role = this.state.roleData;
    if (role === "") {
      return;
    }
    for(let i = 0; i < t_role.length; i++) {
      if(t_role[i]["role"].indexOf(role) !== -1) {
        f_role.push(t_role[i]);
      }
    }
    this.setState({
      roleDataShow: f_role,
    })
  }
  setAddRoleName = (e) => {
    let role = e.target.value;
    this.setState({
      addRoleName: role,
    })
  }
  cancelEdit = () => {
    this.setState({
      cur_tab: "roleList",
      addRoleName: "",
    })
  }
  trim = (str) => { //删除左右两端的空格
    return str.replace(/(^\s*)|(\s*$)/g, "");
  }
  ltrim = (str) => { //删除左边的空格
    return str.replace(/(^s*)/g,"");
  }
  rtrim = (str) => { //删除右边的空格
    return str.replace(/(s*$)/g,"");
  }
  comfirmAddRole = () => {
    let roleName = this.trim(this.state.addRoleName);
    if (roleName === "") {
      alert("请输入角色名");
      this.setState({
        addRoleName: "",
      })
      return;
    }
    let right = this.state.pageListRight;
    let page_list = [];
    for(let i = 0; i < right.length; i++){
      page_list.push(right[i]["page_path"]);
    }
    this.add_or_alter_role(roleName, page_list);
  }
  has = (list, item, key) => {
    for(let i = 0; i < list.length; i++){
      if(item[key] === list[i][key]) {
        return true;
      }
    }
    return false;
  }
  shiftRight = (records) => {
    let left = [];
    let right = [...this.state.pageListRight];
    let pageList = [...this.state.pageListLeft];
    for(let i = 0; i < pageList.length; i++){
      pageList[i].checked = false;
      if(records.indexOf(pageList[i]["id"]) === -1) {
        if(!this.has(left, pageList[i], "id")) {
          left.push(pageList[i]);
        }
      } else {
        if(!this.has(right, pageList[i], "id")) {
          right.push(pageList[i]);
        }
      }
    }
    this.setState({
      pageListLeft: left,
      pageListRight: right,
    })
  }
  shiftLeft = (records) => {
    let left = [...this.state.pageListLeft];
    let right = [];
    let pageList = [...this.state.pageListRight];
    for(let i = 0; i < pageList.length; i++){
      pageList[i].checked = false;
      if(records.indexOf(pageList[i]["id"]) === -1) {
        if(!this.has(right, pageList[i], "id")) {
          right.push(pageList[i]);
        }
      } else {
        if(!this.has(left, pageList[i], "id")) {
          left.push(pageList[i]);
        }
      }
    }
    this.setState({
      pageListLeft: left,
      pageListRight: right,
    })
  }
  render() {
    let isRoleListShow = this.state.cur_tab === "roleList" ? "block" : "none";
    let isRoleDetailShow = this.state.cur_tab === "roleDetail" ? "block" : "none";
    return (
      <div align='center'>
        <MenuHead/>
        <h4>角色配置</h4>
        <div style={{display: `${isRoleListShow}`}}>
          <table>
          <tbody>
          <tr>
          <td><button onClick={this.addRole}>新增角色</button></td>
          <td>
            <input type="text" 
              onChange={this.filterRoleQuery} 
              size="12" maxLength="12" ></input>
          </td>
          </tr>
          </tbody>
          </table>
          <Table
            head={this.state.roleHead}
            data={this.state.roleDataShow}
            queryData={this.queryRoleList}
            deleteData={this.batchDelRoleList}
            modifyData={this.modifyRoleList}
            recordCount={this.state.roleList_count} />
        </div>
        <div style={{display: `${isRoleDetailShow}`}}>
          <table>
          <tbody>
          <tr>
          <td><button onClick={this.cancelEdit}>取消</button></td>
          <td width='20'></td>
          <td><button onClick={this.comfirmAddRole}>确定</button></td>
          </tr>
          </tbody>
          </table>
          <table>
          <tbody>
          </tbody>
          </table>
          <table>
          <tbody>
          <tr>
            <td><span>角色: </span></td>
            <td>
              <input type="text" 
              onChange={this.setAddRoleName} 
              size="12" maxLength="12"
              readOnly={this.state.add_role_input_read_only}
              value={this.state.addRoleName}></input>
            </td>
          </tr>
          </tbody>
          </table>
          <table>
          <tbody>
          <tr>
          <td>
          <TableL 
            head={this.state.pageHead}
            data={this.state.pageListLeft}
            filter={["abs_path"]}
            deleteName={"右移"}
            deleteData={this.shiftRight}/>
          </td>
          <td>
          <TableL 
            head={this.state.pageHead}
            data={this.state.pageListRight}
            filter={["abs_path"]}
            deleteName={"左移"}
            deleteData={this.shiftLeft}/>
          </td>
          </tr>
          </tbody>
          </table>
        </div>
      </div>
    )
  }
}

export default Role;
